package com.erdos.upc.web.intercept;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.erdos.common.service.AppServiceHelper;
import com.erdos.upc.core.UpcConst;
import com.erdos.upc.core.UpcUser;
import com.erdos.upc.core.UpcUtil;
import com.erdos.upc.entity.Privilege;
import com.erdos.upc.entity.User;
import com.erdos.upc.service.PrivilegeService;
import com.erdos.upc.service.UserService;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AccessInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 4902659316661434770L;
	
	private static final Log logger = LogFactory.getLog(AccessInterceptor.class);
	
	/** 定义开发模式参数，便于开发期间调试，后期可以去掉 */
	private boolean dev=false;

	public void setDev(boolean dev) {
		this.dev = dev;
	}
	
	private PrivilegeService privilegeService;

	public void setPrivilegeService(PrivilegeService privilegeService) {
		this.privilegeService = privilegeService;
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		logger.debug("start access privilege check...");	
		
		//如果是开发模式，直接放行
		if (dev) {
			logger.debug("running at develop mode,skip privilege check!");
			return invocation.invoke();
		}
		
		HttpServletRequest request = ServletActionContext.getRequest();
		UpcUser upcUser=UpcUtil.getUpcUser(request);
		
		String uri = request.getServletPath();
		String url=uri;
		String queryString=request.getQueryString();
		if(StringUtils.isNotEmpty(queryString)){
			url=uri+"?"+queryString;
		}
		if (upcUser == null) {//没有检测到登录信息	
			if (uri.indexOf("listenerManage") != -1 || uri.indexOf("cacheFlushApp") != -1) {//如果是监听器管理或缓存刷新相关
				Map<String, Object> params = new HashMap<String, Object>();
				String authLoginId = request.getParameter("authLoginId");
				String authLoginPasswd = request.getParameter("authLoginPasswd");
				if(null != authLoginId && null != authLoginPasswd){
					params.put("pin", authLoginId);
					params.put("password", authLoginPasswd);
					UserService userService = (UserService) AppServiceHelper
							.findBean("userService");
					User user = userService.findUniqueByParams(params);
					if (user != null) {
						upcUser = new UpcUser();
						upcUser.setLoginId(authLoginId);
						upcUser.setLoginGroup("1");
						upcUser.setLoginShift("1");
						upcUser.setFacilityIds("");
						request.getSession().setAttribute(UpcConst.LOGIN_UPC_USER, upcUser);
						return invocation.invoke();
					}
				}
				return "invalidLogin";
			}else{			
				logger.debug("not login request uri=" + url);
				//判断是不是访问登录登出请求，如果是也直接放行，否则转向登录提示界面
				if (url.startsWith("/login") || url.startsWith("/logout")) {
					logger.debug("login/logout request,pass request");
					return invocation.invoke();
				}else{
					logger.debug("not login access,take to login tip page");
					return "invalidLogin";
				}
			}
		} else {//有登录信息，进一步检测访问权限
			logger.debug("login request uri="+ url+",check privilege...");
			Set<Privilege> privileges=upcUser.getPrivileges();
			if(privileges==null){
				privileges=new HashSet<Privilege>();
			}
			for(Privilege privilege:privileges){
				if(privilege!=null&&privilege.getUrl()!=null&&url.indexOf(privilege.getUrl())>-1){//有访问权限，直接放行
					logger.debug("have privilege,pass request");
					return invocation.invoke();
				}
			}
			//进一步检查该URI是否受权限保护
			List<Privilege> allPrivileges=privilegeService.findAll();
			for(Privilege p:allPrivileges){
				if(p.getUrl()!=null&&url.indexOf(p.getUrl())>-1){//该URL是受保护地址，则转向未授权访问提示
					logger.debug("don't have privilege,take to access denied page");
					return "accessDenied";
				}
			}
			//该URL是不受保护，可自由访问
			logger.debug("url don't need protect.pass request");
			return invocation.invoke();
		}
	}
	
}
